package com.test.mooan.labama.activity_fragment_boom.login_boom;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.IntentSenderRequest;
import androidx.activity.result.contract.ActivityResultContracts;

import com.google.android.gms.auth.api.identity.GetPhoneNumberHintIntentRequest;
import com.google.android.gms.auth.api.identity.Identity;
import com.test.mooan.labama.R;
import com.test.mooan.labama.activity_fragment_boom.base_boom.BaseLoginActivity_boom;
import com.test.mooan.labama.activity_fragment_boom.ln_boom.LnApplyActivity_boom;
import com.test.mooan.labama.activity_fragment_boom.ln_boom.LnMainActivity_boom;
import com.test.mooan.labama.bean_boom.config_info_boom.AppShowInfo_boom;
import com.test.mooan.labama.bean_boom.config_info_boom.CountryInfo_boom;
import com.test.mooan.labama.bean_boom.process_boom.ProcessInfo_boom;
import com.test.mooan.labama.bean_boom.user_info_boom.LoginInfo_boom;
import com.test.mooan.labama.utils_boom.Stringutil_boom;
import com.test.mooan.labama.utils_boom.helper_boom.UserInfoHelper_boom;
import com.test.mooan.labama.utils_boom.http_boom.HttpManager_boom;
import com.test.mooan.labama.view_boom.widget_boom.BoomEditText;

import org.json.JSONException;
import org.json.JSONObject;


public class LoginPhoneNumActivity_boom extends BaseLoginActivity_boom {

    private BoomEditText phonenumEt;
    private TextView mobileInputTitleTv;
    private Button nextBtn;

    private ImageButton agreementIb;

    private boolean agreementFlag = true;

    private boolean phoneNumberHintFlag = true;

    private final ActivityResultLauncher<IntentSenderRequest> phoneNumberHintLauncher = registerForActivityResult(
            new ActivityResultContracts.StartIntentSenderForResult(),
            result -> {
                try {

                    String mobile = Identity.getSignInClient(this).getPhoneNumberFromIntent(result.getData());

                    if (TextUtils.isEmpty(mobile)) return;

                    String areaCodeText = CountryInfo_boom.gInstance().gAreaCode();

                    if (mobile.startsWith(areaCodeText)) phonenumEt.setText(mobile.replace(areaCodeText,""));
                    else phonenumEt.setText(mobile);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    );

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_phone_num_boom);
        pageTag = "LOGIN_PHONE";

        TextView areaCodeTv = findViewById(R.id.activity_login_phone_num_tv_area_code);
        phonenumEt = findViewById(R.id.activity_login_phone_num_et_phone_num);
        mobileInputTitleTv = findViewById(R.id.activity_login_phone_num_tv_mobile_input_title);
        nextBtn = findViewById(R.id.activity_login_phone_num_btn_next);
        agreementIb = findViewById(R.id.acloginmobile_ib_agreement);

        phonenumEt.stEventWord(pageTag+"MOBILE_INPUT");

        agreementIb.setOnClickListener(v -> setAgreementFlag(!agreementFlag));
        findViewById(R.id.acloginmobile_tv_agreement).setOnClickListener(v -> {

            UserInfoHelper_boom.gInstance().addEventPoint((pageTag + "_STATEMENT_CLICK").toUpperCase());

            Uri uri = Uri.parse(Stringutil_boom.getSafeString(CountryInfo_boom.gInstance().gPrivacyPolicyUrl()));
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);

        });

        areaCodeTv.setText(CountryInfo_boom.gInstance().gAreaCode());

        init();

    }

    @SuppressLint("SetTextI18n")
    private void init() {

        if (CountryInfo_boom.gInstance().isKenya())
            mobileInputTitleTv.setText(getString(R.string.activity_login_enter_phone_num_ksh));
        else mobileInputTitleTv.setText(getString(R.string.enter_phone_number));

        //自动登录
        if (UserInfoHelper_boom.gInstance().didLogin()){
            phonenumEt.setText(UserInfoHelper_boom.gInstance().gMobile());

            try {
                JSONObject object = new JSONObject();
                object.put("token", UserInfoHelper_boom.gInstance().gToken());
                object.put("userId", UserInfoHelper_boom.gInstance().gUserId());
                object.put("typ", UserInfoHelper_boom.LOGIN_TYPE_OLD);
                object.put("isAdSource",UserInfoHelper_boom.gInstance().gIsAdSource() ? "YES":"NO");
                LoginInfo_boom.parse(object);
                onUserLoginResponse_boom();
            }catch (JSONException e){
                e.printStackTrace();
            }

            return;
        }

        phonenumEt.addOnFocusChangeListener((v, hasFocus) -> {

            if (hasFocus && phoneNumberHintFlag){

                phoneNumberHintFlag = false;

                GetPhoneNumberHintIntentRequest request = GetPhoneNumberHintIntentRequest.builder().build();

                Identity.getSignInClient(this).getPhoneNumberHintIntent(request)
                        .addOnSuccessListener(result -> {
                            try {
                                phoneNumberHintLauncher.launch(new IntentSenderRequest.Builder(result.getIntentSender()).build());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        })
                        .addOnFailureListener(e -> Log.e("=Login", "Phone number hint failed"));

            }

        });

        nextBtn.setOnClickListener(v -> {

            String phonenum = Stringutil_boom.getSafeString(phonenumEt.gtTextString());

            UserInfoHelper_boom.gInstance().addEventPoint((pageTag + "_CONFIRM_CLICK").toUpperCase(),phonenum);

            if (TextUtils.isEmpty(phonenum)) {
                showToast_boom(getString(R.string.enter_phonenum_tip));
                return;
            }
            
            HttpManager_boom.getInstance().saveUserPointForBatch();

            //测试账号登录
            String accountToken = AppShowInfo_boom.getInstance().isTestAccount(phonenum);
            if (!TextUtils.isEmpty(accountToken)) {
                try {
                    JSONObject object = new JSONObject();
                    object.put("token", accountToken);
                    object.put("userId", phonenum);
                    object.put("typ", UserInfoHelper_boom.LOGIN_TYPE_OLD);
                    object.put("isAdSource","NO");
                    UserInfoHelper_boom.gInstance().sMobile(phonenum);
                    LoginInfo_boom.parse(object);
                    onUserLoginResponse_boom();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return;
            }

            HttpManager_boom.getInstance().userLoginNoCode(phonenum);

        });

    }

    @Override
    public void onRequestOtpCodeResponse_boom(JSONObject jsonObject) {

//        String msg = BaseApplication_boom.getInstant_boom().getMsg();
//
//        String phonenum = phonenumEt.gtTextString();
//
//        if (jsonObject!=null){
//            String directLoginFlag = Stringutil_boom.getSafeString(jsonObject.optString("directLoginFlag"));
//            //不需要验证码直接登录
//            if (directLoginFlag.equalsIgnoreCase("YES")) {
//                HttpManager_boom.getInstance().userLoginOldUser(Stringutil_boom.getSafeString(phonenum));
//                return;
//            }
//        }
//
//        UserInfoHelper_boom.getInstance().setMobile(phonenum);
//        startActivity_boom(LoginVerCodeActivity_boom.class);

    }

    public void setAgreementFlag(boolean agreementFlag) {
        this.agreementFlag = agreementFlag;
        agreementIb.setBackgroundResource(agreementFlag ? R.drawable.icon_item_check_true:R.drawable.icon_item_check_false);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (phonenumEt!=null) phonenumEt.clearFocus();
    }

    @Override
    public void onUserProcessResponse(){
        //手机号后置校验
        if (ProcessInfo_boom.getInstance().isNeedVerification()){
            if (CountryInfo_boom.gInstance().isCambodia()) startActivity(new Intent(this,MobileVerificationActivity.class).putExtra("toHomeFlag",true));
            else startActivity(new Intent(this,MobileVerificationActivity2.class).putExtra("toHomeFlag",true));
            finish();
            return;
        }

        startActivityForSingleTop_boom(LnMainActivity_boom.class);
    }

}